const knex = require("./knex");

async function createOrUpdateTable(tableName, fields) {
  const tableExists = await knex.schema.hasTable(tableName);
  if (!tableExists) {
    await createTable(tableName, fields);
  } else {
    await updateTable(tableName, fields);
  }
}

async function createTable(tableName, fields) {
  await knex.schema
    .createTable(tableName, (table) => {
      table.increments("_id");
      Object.entries(fields).forEach(([fieldName, type]) => {
        table[type](fieldName).defaultTo(null);
        if (tableName === 'users' && fieldName === 'phone') {
          table.unique('phone')
        }
      });
      table.timestamps(false, true);
    })
    .then(() => {
      console.log(`${tableName} table created`);
    })
    .catch((err) => {
      console.log(err, 222);
      throw err;
    });
}

async function updateTable(tableName, newFields) {
  const currentFields = await knex(tableName).columnInfo();
  const fieldsToAdd = {};
  const fieldsToDelete = [];

  // 找到需要添加的新字段
  Object.entries(newFields).forEach(([fieldName, type]) => {
    if (!currentFields[fieldName]) {
      fieldsToAdd[fieldName] = type;
    }
  });

  // 找到需要删除的旧字段
  Object.keys(currentFields).forEach((fieldName) => {
    if (!newFields[fieldName]) {
      fieldsToDelete.push(fieldName);
    }
  });

  // 向表中添加新字段
  if (Object.keys(fieldsToAdd).length > 0) {
    await knex.schema
      .alterTable(tableName, (table) => {
        Object.entries(fieldsToAdd).forEach(([fieldName, type]) => {
          table[type](fieldName).defaultTo(null);
          if (tableName === 'users' && fieldName === 'phone') {
            table.unique('phone')
          }
        });
      })
      .then(() => {
        console.log(`New fields added to ${tableName} table`);
      })
      .catch((err) => {
        console.log(err, 1111);
        throw err;
      });
  }

  // 从表中删除旧字段
  if (fieldsToDelete.length > 0) {
    await knex.schema
      .alterTable(tableName, (table) => {
        fieldsToDelete.forEach((fieldName) => {
          if (fieldName !== "_id" && fieldName!== "created_at" && fieldName!== "updated_at") {
            // 排除自增字段
            table.dropColumn(fieldName);
          }
        });
      })
      .then(() => {
        console.log(`Fields deleted from ${tableName} table`);
      })
      .catch((err) => {
        console.log(err, 333);
        throw err;
      });
  }
}

module.exports = {
  createOrUpdateTable,
  createTable,
  updateTable,
};
